package com.xbongbong.saas.analytical.impl;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.help.team.TeamUserHelp;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.pro.enums.ErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ClueErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.saas.analytical.SaasValidateAnalyticalService;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.MarketActivityEnum;
import com.xbongbong.saas.help.SaasDataInitHelp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 吴峰
 * @date 2021/07/15 17:15
 */
@Service("marketActivityAnalyticalServiceImpl")
public class MarketActivityValidateAnalyticalServiceImpl implements SaasValidateAnalyticalService {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(MarketActivityValidateAnalyticalServiceImpl.class);
    
    @Resource
    private TeamUserHelp teamUserHelp;

    @Override
    public List<Integer> type() {
        return Arrays.asList(XbbRefTypeEnum.MARKET_ACTIVITY.getCode());
    }

    @Override
    public void analyticalData(ValidateDataDTO validateDataDTO) throws XbbException {
        beforeSave(validateDataDTO);
        if (!Objects.equals(validateDataDTO.getFromOuterLink(), BasicConstant.ONE)) {
            teamUserHelp.beforeVerifyUserTeam(validateDataDTO);
        }
    }
    
    public void beforeSave(ValidateDataDTO validateDataDTO) throws XbbException {
        try {
            JSONObject data = validateDataDTO.getData();
            if(Objects.isNull(data)){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100019);
            }
            //结束时间必须大于开始时间
            Long startTime = data.getLong(MarketActivityEnum.START_TIME.getAttr());
            Long endTime = data.getLong(MarketActivityEnum.END_TIME.getAttr());
            if(Objects.nonNull(startTime) && Objects.nonNull(endTime) && (endTime < startTime)){
                throw new XbbException(ClueErrorCodeEnum.API_ERROR_1100200);
            }
            // 赋予默认值 (金额成本为 0 )
            for (Map.Entry<String,Object> entry : SaasDataInitHelp.initMarketActivity().entrySet()){
                SaasDataInitHelp.antDataSet(data,entry.getKey(),entry.getValue());
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOGGER.error("clueAnalyticalServiceImpl.beforeSave error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }
}
